package com.azr.jesus.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.azr.jesus.common.dto.UserDTO;
import com.azr.jesus.common.dto.UserPasswordDTO;
import com.azr.jesus.common.domain.HttpStatus;
import com.azr.jesus.common.utils.EasyExcelUtil;
import com.azr.jesus.entity.User;
import com.azr.jesus.common.domain.ResultData;
import com.azr.jesus.service.IUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 用户信息表
 * @author:: Xiong
 * @date:: 2022/10/30 19:44
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    IUserService userService;

    /**
     * 用户登录
     *
     * @param userDto
     * @return
     */
    @PostMapping("/login")
    @ApiOperation(value = "登录")
    public ResultData login(@RequestBody UserDTO userDto) {
        String username = userDto.getUserName();
        String password = userDto.getPassword();
        if (StrUtil.isBlank(username) && StrUtil.isBlank(password)) {
            return ResultData.error(HttpStatus.BAD_REQUEST, "参数异常");
        }
        return ResultData.success(userService.login(userDto));
    }

    /**
     * 注册用户
     *
     * @param userDto
     * @return
     */
    @PostMapping("/register")
    @ApiOperation(value = "注册")
    public ResultData register(@RequestBody UserDTO userDto) {
        String username = userDto.getUserName();
        String password = userDto.getPassword();
        if (StrUtil.isBlank(username) && StrUtil.isBlank(password)) {
            return ResultData.error(HttpStatus.BAD_REQUEST, "参数异常");
        }
        return ResultData.success(userService.register(userDto));
    }

    @PostMapping("/password")
    @ApiOperation(value = "修改密码")
    public ResultData password(@RequestBody UserPasswordDTO userPasswordDTO) {
        userPasswordDTO.setPassword(SecureUtil.md5(userPasswordDTO.getPassword()));
        userPasswordDTO.setNewPassword(SecureUtil.md5(userPasswordDTO.getNewPassword()));
        return ResultData.success(userService.updatePassword(userPasswordDTO));
    }

    /**
     * 查询全部数据
     *
     * @return
     */
    @GetMapping
    @ApiOperation(value = "获取用户列表")
    public ResultData findAll() {
        return ResultData.success(userService.list());
    }

    /**
     * 根据名称查询用户
     *
     * @param username
     * @return
     */
    @GetMapping("/username/{username}")
    @ApiOperation(value = "根据名称查询用户")
    public ResultData findOne(@PathVariable String username) {
        QueryWrapper<User> wrapper = new QueryWrapper<User>();
        wrapper.eq("user_name", username);
        return ResultData.success(userService.getOne(wrapper));
    }

    /***
     * 根据ID查询数据
     * @param userId
     * @return
     */
    @GetMapping("/{userId}")
    @ApiOperation(value = "根据ID查询用户")
    public ResultData findById(@PathVariable String userId) {
        return ResultData.success(userService.getById(userId));
    }

    /***
     * 新增数据
     * @param user
     * @return
     */
    @PostMapping
    @ApiOperation(value = "新增用户")
    public ResultData add(@RequestBody User user) {
        user.setCreateTime(new Date());
        return ResultData.success(userService.saveOrUpdate(user));
    }

    /***
     * 修改数据
     * @param user
     * @return
     */
    @PutMapping
    @ApiOperation(value = "修改用户信息")
    public ResultData update(@RequestBody User user) {
        user.setUpdateTime(new Date());
        return ResultData.success(userService.updateById(user));
    }

    /***
     * 根据ID删除数据
     * @param userId
     * @return
     */
    @DeleteMapping(value = "/{userId}")
    @ApiOperation(value = "删除用户")
    public ResultData delete(@PathVariable String userId) {
        return ResultData.success(userService.removeById(userId));
    }

    /***
     * 根据ID删除数据
     * @param ids
     * @return
     */
    @PostMapping(value = "/batchDelete")
    @ApiOperation(value = "批量删除用户")
    public ResultData batchDelete(@RequestBody List<Integer> ids) {
        return ResultData.success(userService.removeBatchByIds(ids));
    }

    /**
     * 分页搜索实现
     *
     * @param pageNum
     * @param pageSize
     * @param nickName
     * @param email
     * @param phonenumber
     * @return
     */
    @GetMapping(value = "/page")
    @ApiOperation(value = "分页查询用户")
    public ResultData findPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize,
                               @RequestParam String nickName, @RequestParam String email,
                               @RequestParam String phonenumber) {
        QueryWrapper<User> query = new QueryWrapper<>();
        if (StrUtil.isNotBlank(nickName)) {
            query.like("nick_name", nickName);
        }
        if (StrUtil.isNotBlank(email)) {
            query.like("email", email);
        }
        if (StrUtil.isNotBlank(phonenumber)) {
            query.like("phonenumber", phonenumber);
        }
        return ResultData.success(userService.page(new Page<>(pageNum, pageSize), query));
    }

    @GetMapping("/export")
    @ApiOperation(value = "Excel导出")
    public void export(HttpServletResponse response) throws IOException {
        List<User> userList = userService.list();
        EasyExcelUtil.download(response, userList, "用户信息表");
    }

    @PostMapping("/import")
    public ResultData importUser(@RequestPart("file") MultipartFile file) throws Exception {
        List<User> users = EasyExcelUtil.read(file.getInputStream(), User.class);
        return ResultData.success(userService.saveBatch(users));
    }

    @GetMapping("/userRole/{userId}")
    @ApiOperation(value = "获取用户和角色的关系")
    public ResultData getUserRole(@PathVariable Long userId) {
        return ResultData.success(userService.getRoleMenu(userId));
    }

    @PostMapping("/userRole/{userId}")
    @ApiOperation(value = "绑定用户和角色的关系")
    public ResultData roleMenu(@PathVariable Long userId, @RequestBody List<Long> roleIds) {
        userService.setUserRole(userId, roleIds);
        return ResultData.success();
    }
}
